<script>
	export default {
		onLaunch() {
			let that = this
			// #ifdef APP
			this.setupPermissionListener();
			// #endif
			// #ifdef MP-WEIXIN
			this.checkForUpdates();
			// #endif 
			uni.onNetworkStatusChange(function(res) {
				if (res.isConnected) {
					const userinfo = uni.getStorageSync('userinfo');
					if (userinfo) {
						that.ws.init(userinfo.token, userinfo.auth_token)
					}
				} else {
					that.ws.socketTask.close()
					that.ws.socketOpen = false
					that.ws.checkNetwork()
				}
			});
		},
		onShow() {
			this.ws.pageRefresh.message = true
			this.ws.pageRefresh.sessionInfo = true
			this.checkLogin()
		},
		onHide() {
			console.log('App Hide');
		},
		methods: {
			checkForUpdates: function() {
				if (wx.canIUse('getUpdateManager')) {
					const updateManager = wx.getUpdateManager();
			
					updateManager.onCheckForUpdate(function(res) {
						// 请求完新版本信息的回调
						console.log('Has update:', res.hasUpdate);
					});
			
					updateManager.onUpdateReady(function() {
						wx.showModal({
							title: '更新提示',
							content: '新版本已经准备好，是否重启应用？',
							showCancel: false, // 不允许取消
							success: function(res) {
								if (res.confirm) {
									// 强制更新小程序
									updateManager.applyUpdate();
								}
							}
						});
					});
			
					updateManager.onUpdateFailed(function() {
						// 新版本下载失败
						wx.showModal({
							title: '更新失败',
							content: '新版本下载失败，请检查网络设置或重试。',
							showCancel: false // 不允许取消
						});
					});
				} else {
					// 兼容处理，不支持 `getUpdateManager` 的低版本微信
					wx.showModal({
						title: '提示',
						content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
						showCancel: false // 不允许取消
					});
				}
			},
			setupPermissionListener() {
				const permissionListener = uni.createRequestPermissionListener();
				permissionListener.onConfirm((e) => {
					console.log(e)
				});
				permissionListener.onComplete((e) => {
					console.log(e)
				});
			},
			checkLogin: function() {
				const userinfo = uni.getStorageSync('userinfo');
				var valid = true;
				if (!userinfo || !userinfo.token) {
					valid = false;
				} else {
					let token = userinfo.token.split('|');
					let time = Date.parse(new Date()).toString();
					time = time.substr(0, 10);
					// 减去一秒,防止刚好到时间造成发送了错误的请求
					if ((parseInt(token[2]) - 2) < parseInt(time)) {
						valid = false;
					}
				}

				if (!valid) {
					setTimeout(() => {
						this.ws.logout()
					}, 300)
				} else {
					this.ws.init(userinfo.token, userinfo.auth_token)
				}
			}
		}
	}
</script>
<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-ui/index.scss";

	.user-status-0 {
		color: #999999 !important;
	}

	.user-status-1 {
		color: #21E589 !important;
	}

	.user-status-2 {
		color: #FF647E !important;
	}

	.user-status-3 {
		color: #FF9C4E !important;
	}

	view {
		box-sizing: border-box;
	}
</style>